class Calculator {
    constructor() {
        this.displayElement = document.getElementById('display');
        this.buttonsContainer = document.querySelector('.buttons');
        this.initialize();
    }

    initialize() {
        // 事件委托处理按钮点击
        this.buttonsContainer.addEventListener('click', (event) => {
            const button = event.target;
            const action = button.dataset.action;
            const value = button.dataset.value;

            if (action) {
                this.handleAction(action);
            } else if (value) {
                this.appendToDisplay(value);
            }
        });

        // 支持键盘输入
        document.addEventListener('keydown', (event) => {
            const key = event.key;
            if (/[\d+\-*/.()]/.test(key)) {
                this.appendToDisplay(key);
            } else if (key === 'Enter') {
                this.calculate();
            } else if (key === 'Backspace') {
                this.backspace();
            } else if (key === 'Escape') {
                this.clearDisplay();
            }
        });
    }

    appendToDisplay(value) {
        if (this.displayElement.value.length >= 50) return; // 限制输入长度
        this.displayElement.value += value;
    }

    clearDisplay() {
        this.displayElement.value = '';
    }

    backspace() {
        this.displayElement.value = this.displayElement.value.slice(0, -1);
    }

    calculate() {
        try {
            const expression = this.displayElement.value;
            const result = this.safeEval(expression);
            this.displayElement.value = result;
        } catch (error) {
            this.displayElement.value = '错误';
        }
    }

    safeEval(expression) {
        // 简单的表达式校验
        if (!/^[\d+\-*/.()\s]+$/.test(expression)) {
            throw new Error('非法输入');
        }
        // 使用 Function 构造函数替代 eval
        return new Function(`return ${expression}`)();
    }

    handleAction(action) {
        switch (action) {
            case 'clear':
                this.clearDisplay();
                break;
            case 'backspace':
                this.backspace();
                break;
            case 'calculate':
                this.calculate();
                break;
            default:
                break;
        }
    }
}

const calculator = new Calculator();